#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <sys/select.h>

#include "om.h"

void milliseconds_sleep(unsigned long mSec) {
  struct timeval tv;
  tv.tv_sec = mSec / 1000;
  tv.tv_usec = (mSec % 1000) * 1000;
  int err;
  do {
    err = select(0, NULL, NULL, NULL, &tv);
  } while (err < 0 && errno == EINTR);
}

om_status_t print_log(om_msg_t *msg, void *arg) {
  om_log_t *log = (om_log_t *)msg->buff;
  struct tm *time;
  time = localtime(&(log->time));
  printf("[%04d-%02d-%02d %02d:%02d:%02d]:%s", time->tm_year + 1900,
         time->tm_mon + 1, time->tm_mday, time->tm_hour, time->tm_min,
         time->tm_sec, (char *)log->data);

  return OM_OK;
}

bool thd_continue = true;
int i = 0;

void *thread(void *arg) {
  (void)arg;
  while (thd_continue) {
    OMLOG_DEFAULT("This is log %d.", i++);
    milliseconds_sleep(1);
  }
  OMLOG_NOTICE("Thread End.");
  pthread_exit(0);
}

int main() {
  om_init();

  om_topic_t *topic_log = om_get_log_handle();

  om_config_topic(NULL, "TCDA", "test", 100, topic_log, print_log, NULL);

  pthread_t t1, t2;
  OMLOG_PASS("OneMessage start.");
  OMLOG_WARNING("This is OneMessage example.");
  OMLOG_WARNING("Thread1 init.");
  pthread_create(&t1, NULL, thread, NULL);
  OMLOG_WARNING("Thread2 init.");
  pthread_create(&t2, NULL, thread, NULL);
  milliseconds_sleep(1000);

  thd_continue = false;

  milliseconds_sleep(10);

  OMLOG_PASS("log num:%d.", i + 1);

  OMLOG_ERROR("OneMessage exit.");
}